package pingce.share.util;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

import pingce.share.model.PairValue;

public class EmoticonProcessor {
	
	private static final String TENCENT_EMOTICONS = "emoticons/tencent";
	
	private List<String> emoticonList ;
	
	private EmoticonProcessor(String emoticonDir)throws Exception{
		File dir = new File(emoticonDir);
		this.emoticonList = new LinkedList<String>();
		if(dir.isDirectory()){
			for(File f : dir.listFiles()){
				this.emoticonList.add("/" + f.getName().substring(0, f.getName().indexOf(".")));
			}
		}
	}
	
	public EmoticonProcessor() throws Exception{
		this(TENCENT_EMOTICONS);
	}
	
	public List<PairValue> getEmoticons(List<PairValue> texts){
		List<PairValue> result = new LinkedList<PairValue>();
		for(PairValue pv : texts){
			if(Integer.parseInt(pv.getAttach()) == WrappedSplitter.NORMAL){
				result.addAll(getEmoticonsFromNormal(pv.getBasic()));
			}else{
				result.add(pv);
			}
		}
		return result;
	}
	
	private List<PairValue> getEmoticonsFromNormal(String text){
		List<PairValue> result = new LinkedList<PairValue>();
		if(text.contains("/")){
			int index = text.indexOf("/");
			int start = 0;
			boolean find = false;
			String str = text.substring(index);
			for(String emoticon : this.emoticonList){
				if(str.startsWith(emoticon)){
					find = true;
					if(index != 0){
					result.add(
							new PairValue(text.substring(0, index), 
									new Integer(WrappedSplitter.NORMAL).toString()));
					}
					result.add(
							new PairValue(emoticon, 
									new Integer(WrappedSplitter.EMOTICON).toString()));
					start = index + emoticon.length();
					break;
				}
			}
			
			if(!find){
				result.add(
						new PairValue(text.substring(0, index + 1),
								new Integer(WrappedSplitter.NORMAL).toString()));
				start = index + 1;
			}
			
			if(start < text.length()){
				result.addAll(getEmoticonsFromNormal(text.substring(start)));
			}
		}else{
			result.add(new PairValue(text, new Integer(WrappedSplitter.NORMAL).toString()));
		}
		
		return result;
	}
	
	public static void main(String[] args)throws Exception{
		String str = "#皮鞋果冻#真恶心，我不吃果冻 /阴险";
		EmoticonProcessor ep = new EmoticonProcessor();
		PairValue pv = new PairValue(str, new Integer(WrappedSplitter.NORMAL).toString());
		List<PairValue> rawList = new LinkedList<PairValue>();
		rawList.add(pv);
		List<PairValue> list = ep.getEmoticons(rawList);
		System.out.println("start to print:" + list.size());
		for(PairValue p : list){
			System.out.println(p.getBasic() + "\t" + p.getAttach());
		}
	}
}
